﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RiskMan.Config;
using RiskMan.DataClass.Models.Quik;
using XlDde;
using RiskMan.DataClass.Models;
using System.Windows.Forms;
using RiskMan.Views.Dialogs;
using System.Reflection;

namespace RiskMan.Providers.Channels
{
    class DDEChannelPositionToClientAccount : XlDdeChannel
    {
        private List<PositionToClientAccountModel> list;

        public DDEChannelPositionToClientAccount()
        {
            
        }

        protected override void ProcessTable(XlTable xt, string topic)
        {
            list = RiskMan.MainWindow.StaticRiskMan._dataProvider.FortsPositionsList;
            try
            {
                for (int i = 0; i < xt.Rows; i++)
                {
                    PositionToClientAccountModel tmp = new PositionToClientAccountModel();
                    List<String> names = new List<String>();

                    for (int j = 0; j < xt.Columns; j++)
                    {
                        xt.ReadValue();
                        if (Namespace.Count == 0 && i == 0)
                        {
                            tmp = null;
                            names.Add(xt.StringValue);
                        }
                        else
                        {
                            if ( IsSend( xt ) == true )
                            {
                                try
                                {
                                    if ( Namespace [ j ] == "FIRMID" ) tmp.Company = xt.StringValue;
                                    if ( Namespace [ j ] == "TRDACCID" ) tmp.Account = xt.StringValue;
                                    if ( Namespace [ j ] == "SECCODE" ) tmp.Seccode = xt.StringValue;
                                    if ( Namespace [ j ] == "SEC_EXPIRY_DATE" ) tmp.DataExpiration = DateTime.Parse( xt.StringValue );
                                    if ( Namespace [ j ] == "START_BUY" ) tmp.EnterLongPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "START_SELL" ) tmp.EnterShortPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "START_NET" ) tmp.EnterEmptyPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "TODAY_BUY" ) tmp.CurrentLongPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "TODAY_SELL" ) tmp.CurrentShortPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "TOTAL_NET" ) tmp.CurrentEmptyPos = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "OPEN_BUYS" ) tmp.ActiveBuy = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "OPEN_SELLS" ) tmp.ActiveSell = ( int ) xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLUSED" ) tmp.MarkCurrentEmptyPos = xt.FloatValue;
                                    if ( Namespace [ j ] == "CBPLPLANNED" ) tmp.PlanEmptyPos = xt.FloatValue;
                                    if ( Namespace [ j ] == "VARMARGIN" ) tmp.VariableMarga = xt.FloatValue;
                                    if ( Namespace [ j ] == "AVRPOSNPRICE" ) tmp.EffectPricePos = xt.FloatValue;
                                    if ( Namespace [ j ] == "POSITIONVALUE" ) tmp.CostPos = xt.FloatValue;
                                }
                                catch ( ArgumentOutOfRangeException )
                                {
                                    string message = "\"Позиции по клиентским счетам\" в разных терминалах настроены по разному. \n\r" +
                                            "Для правильной настройки таблице ознакомьтесь с инструкцией." +
                                            "\n\rНеобходимо чтоб название и количество выводимых параметров совпадало.";
                                    string title = "Ошибка";
                                    if ( base.IsShowMessage == false )
                                    {
                                        base.IsShowMessage = true;
                                        new DialogMessage( message, title );
                                    }
                                    cfg.SetLog( message, RiskMan.MainWindow.StaticRiskMan.ListBox_Logs, GetType( ), MethodBase.GetCurrentMethod( ) );
                                }
                                catch ( Exception ex )
                                {
                                    new DialogMessage( ex.Message, "DDEChannelPositionToClientAccount" );
                                }
                            }
                            else
                            {
                                tmp = null;

                            }
                        }
                    }
                    if (tmp != null)
                    {
                        bool tr = false;
                        for (int r = 0; r < list.Count; r++)
                            if (list[r].Seccode == tmp.Seccode && 
                                list[r].Account == tmp.Account &&
                                list[r].Company == tmp.Company
                                )
                            {
                                tr = true;
                                list[r] = tmp;
                            }
                        if (tr == false)
                            list.Add(tmp);
                    }
                    if (names.Count > 0)
                        Namespace = new List<String>(names);
                }
            }
            catch (Exception ex)
            {
                new DialogOkCancel( ex.Message, "DDEChannelPositionToClientAccount" );
            }
        }

        public override void Disconnected(bool isConnected)
        {
            QuikIntegration.dde.QuikUtil.StartDDE();
            Namespace.Clear();
        }
    }
}
